"""
演示数据加载器
用于在演示模式下加载虚拟岗位和候选人数据
"""

import json
import asyncio
from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
import logging

# 设置日志
logger = logging.getLogger(__name__)

class DemoDataLoader:
    def __init__(self):
        self.project_root = Path(__file__).parent.parent.parent
        self.demo_data_dir = self.project_root / "data" / "demo_data"
        self._jobs_cache = None
        self._candidates_cache = None
        self._loaded = False
    
    async def load_all_data(self):
        """加载所有演示数据"""
        if self._loaded:
            return
        
        try:
            await asyncio.gather(
                self._load_jobs(),
                self._load_candidates()
            )
            self._loaded = True
            logger.info("演示数据加载完成")
        except Exception as e:
            logger.error(f"加载演示数据失败: {e}")
            raise
    
    async def _load_jobs(self):
        """加载虚拟岗位数据"""
        jobs_file = self.demo_data_dir / "virtual_jobs.json"
        if jobs_file.exists():
            with open(jobs_file, 'r', encoding='utf-8') as f:
                self._jobs_cache = json.load(f)
            logger.info(f"加载了 {len(self._jobs_cache)} 个虚拟岗位")
        else:
            logger.warning(f"虚拟岗位数据文件不存在: {jobs_file}")
            self._jobs_cache = []
    
    async def _load_candidates(self):
        """加载虚拟候选人数据"""
        candidates_file = self.demo_data_dir / "virtual_candidates.json"
        if candidates_file.exists():
            with open(candidates_file, 'r', encoding='utf-8') as f:
                self._candidates_cache = json.load(f)
            logger.info(f"加载了 {len(self._candidates_cache)} 个虚拟候选人")
        else:
            logger.warning(f"虚拟候选人数据文件不存在: {candidates_file}")
            self._candidates_cache = []
    
    # 岗位相关方法
    async def get_jobs(self, 
                      skip: int = 0, 
                      limit: int = 20,
                      category: Optional[str] = None,
                      location: Optional[str] = None,
                      salary_min: Optional[int] = None,
                      salary_max: Optional[int] = None) -> List[Dict[str, Any]]:
        """获取岗位列表"""
        await self.load_all_data()
        
        jobs = self._jobs_cache.copy()
        
        # 应用过滤条件
        if category:
            jobs = [job for job in jobs if job.get('category') == category]
        
        if location:
            jobs = [job for job in jobs if job.get('location') == location]
        
        if salary_min is not None:
            jobs = [job for job in jobs if job.get('salary_max', 0) >= salary_min]
        
        if salary_max is not None:
            jobs = [job for job in jobs if job.get('salary_min', 0) <= salary_max]
        
        # 分页
        return jobs[skip:skip + limit]
    
    async def get_job_by_id(self, job_id: str) -> Optional[Dict[str, Any]]:
        """根据ID获取岗位详情"""
        await self.load_all_data()
        
        for job in self._jobs_cache:
            if job.get('id') == job_id:
                return job
        return None
    
    async def search_jobs(self, query: str, skip: int = 0, limit: int = 20) -> List[Dict[str, Any]]:
        """搜索岗位"""
        await self.load_all_data()
        
        query_lower = query.lower()
        matching_jobs = []
        
        for job in self._jobs_cache:
            # 在标题、公司名、技能、描述中搜索
            searchable_text = ' '.join([
                job.get('title', ''),
                job.get('company', ''),
                ' '.join(job.get('required_skills', [])),
                job.get('description', '')
            ]).lower()
            
            if query_lower in searchable_text:
                matching_jobs.append(job)
        
        return matching_jobs[skip:skip + limit]
    
    async def get_job_categories(self) -> List[Dict[str, Any]]:
        """获取岗位类别统计"""
        await self.load_all_data()
        
        categories = {}
        for job in self._jobs_cache:
            category = job.get('category', 'OTHER')
            if category not in categories:
                categories[category] = {'category': category, 'count': 0}
            categories[category]['count'] += 1
        
        return list(categories.values())
    
    # 候选人相关方法
    async def get_candidates(self, 
                           skip: int = 0, 
                           limit: int = 20,
                           category: Optional[str] = None,
                           location: Optional[str] = None,
                           experience_min: Optional[int] = None,
                           experience_max: Optional[int] = None) -> List[Dict[str, Any]]:
        """获取候选人列表"""
        await self.load_all_data()
        
        candidates = self._candidates_cache.copy()
        
        # 应用过滤条件
        if category:
            candidates = [c for c in candidates if c.get('category') == category]
        
        if location:
            candidates = [c for c in candidates if c.get('location') == location]
        
        if experience_min is not None:
            candidates = [c for c in candidates if c.get('experience_years', 0) >= experience_min]
        
        if experience_max is not None:
            candidates = [c for c in candidates if c.get('experience_years', 0) <= experience_max]
        
        # 分页
        return candidates[skip:skip + limit]
    
    async def get_candidate_by_id(self, candidate_id: str) -> Optional[Dict[str, Any]]:
        """根据ID获取候选人详情"""
        await self.load_all_data()
        
        for candidate in self._candidates_cache:
            if candidate.get('id') == candidate_id:
                return candidate
        return None
    
    async def search_candidates(self, query: str, skip: int = 0, limit: int = 20) -> List[Dict[str, Any]]:
        """搜索候选人"""
        await self.load_all_data()
        
        query_lower = query.lower()
        matching_candidates = []
        
        for candidate in self._candidates_cache:
            # 在姓名、技能、总结中搜索
            searchable_text = ' '.join([
                candidate.get('name', ''),
                ' '.join(candidate.get('skills', [])),
                candidate.get('summary', ''),
                candidate.get('current_position', '')
            ]).lower()
            
            if query_lower in searchable_text:
                matching_candidates.append(candidate)
        
        return matching_candidates[skip:skip + limit]
    
    async def analyze_resume(self, candidate_id: str) -> Dict[str, Any]:
        """分析候选人简历"""
        candidate = await self.get_candidate_by_id(candidate_id)
        if not candidate:
            return {}
        
        # 生成模拟的分析结果
        skills = candidate.get('skills', [])
        experience = candidate.get('experience_years', 0)
        
        # 计算技能匹配度分数
        skill_score = min(len(skills) * 15, 90)
        experience_score = min(experience * 8, 95)
        education_score = 85 if candidate.get('education') in ['硕士', '博士'] else 75
        
        overall_score = (skill_score + experience_score + education_score) / 3
        
        return {
            "candidate_id": candidate_id,
            "overall_score": round(overall_score, 1),
            "skill_score": skill_score,
            "experience_score": experience_score,
            "education_score": education_score,
            "strengths": [
                f"具备{len(skills)}项核心技能",
                f"{experience}年丰富工作经验",
                f"{candidate.get('education', '本科')}学历背景"
            ],
            "improvements": [
                "可以进一步提升技术深度",
                "建议增加项目管理经验",
                "可以考虑学习新兴技术"
            ],
            "match_percentage": round(overall_score, 1),
            "analysis_date": datetime.now().isoformat()
        }
    
    # 统计相关方法
    async def get_recruitment_stats(self) -> Dict[str, Any]:
        """获取招聘统计数据"""
        await self.load_all_data()
        
        jobs = self._jobs_cache
        candidates = self._candidates_cache
        
        # 计算统计数据
        total_jobs = len(jobs)
        total_candidates = len(candidates)
        active_jobs = len([j for j in jobs if j.get('status') == 'active'])
        
        # 按类别统计
        job_categories = {}
        candidate_categories = {}
        
        for job in jobs:
            category = job.get('category', 'OTHER')
            job_categories[category] = job_categories.get(category, 0) + 1
        
        for candidate in candidates:
            category = candidate.get('category', 'OTHER')
            candidate_categories[category] = candidate_categories.get(category, 0) + 1
        
        # 应用统计
        total_applications = sum(job.get('applications', 0) for job in jobs)
        avg_applications_per_job = total_applications / max(total_jobs, 1)
        
        return {
            "total_jobs": total_jobs,
            "active_jobs": active_jobs,
            "total_candidates": total_candidates,
            "total_applications": total_applications,
            "avg_applications_per_job": round(avg_applications_per_job, 1),
            "job_categories": job_categories,
            "candidate_categories": candidate_categories,
            "updated_at": datetime.now().isoformat()
        }
    
    async def match_candidates_for_job(self, job_id: str, limit: int = 10) -> List[Dict[str, Any]]:
        """为岗位匹配候选人"""
        job = await self.get_job_by_id(job_id)
        if not job:
            return []
        
        await self.load_all_data()
        
        job_skills = set(job.get('required_skills', []))
        job_category = job.get('category')
        matched_candidates = []
        
        for candidate in self._candidates_cache:
            if candidate.get('category') != job_category:
                continue
            
            candidate_skills = set(candidate.get('skills', []))
            
            # 计算技能匹配度
            skill_intersection = job_skills.intersection(candidate_skills)
            skill_match_rate = len(skill_intersection) / max(len(job_skills), 1) * 100
            
            # 计算经验匹配度
            required_exp = job.get('experience_min', 0)
            candidate_exp = candidate.get('experience_years', 0)
            exp_match_rate = min(candidate_exp / max(required_exp, 1) * 100, 100)
            
            # 总体匹配度
            overall_match = (skill_match_rate + exp_match_rate) / 2
            
            if overall_match > 30:  # 只返回匹配度大于30%的候选人
                matched_candidates.append({
                    **candidate,
                    "match_score": round(overall_match, 1),
                    "skill_match_rate": round(skill_match_rate, 1),
                    "experience_match_rate": round(exp_match_rate, 1),
                    "matched_skills": list(skill_intersection)
                })
        
        # 按匹配度排序
        matched_candidates.sort(key=lambda x: x['match_score'], reverse=True)
        
        return matched_candidates[:limit]

# 全局实例
demo_loader = DemoDataLoader()